package org.jeecg.common.Wechat.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.sf.json.JSONException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.DocumentException;
import org.jeecg.common.Wechat.entity.WxTemplate;
import org.jeecg.common.Wechat.util.CommUtil;
import org.jeecg.common.Wechat.util.HttpRequestUtil;
import org.jeecg.common.Wechat.util.HttpRequestUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Description: TODO
 * @author: sn
 * @date: 2021年08月29日 16:39
 */

public class WeiXinController {

    private static final String url="https://api.weixin.qq.com/cgi-bin/token";
    private static final String grant_type="client_credential";

    //鲁维客服中心-2020-12-24更新  ae12a7be352f13572ba1cf21fa6af420
    private static final String app_id="wx14f4b30a9120de55";
    private static final String secret="ae12a7be352f13572ba1cf21fa6af420";
    private static final String htmUrl="";//详情url
    //获取access_token
    public static final String ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+app_id+"&secret="+secret;
    //通过code 获取openId
    public static final String OPENID_BY_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + app_id + "&secret=" + secret + "&grant_type=authorization_code" + "&code=";
    //报修信息推送模板 private static final String bx_template_id="gYSgb2LShqYZ8TNKXpPMpaCHjZDZm5cJTs9RQh1Ch1Y";
    //流程待审批模板
    private static final String check_template_id="yOck0pmsBF-nGlAamB2pJ_NbASt0rkOiNp6ClYk9hEE";





    //获取access_token
    public  String  getToken(){
        HttpClient client=new DefaultHttpClient();
        HttpGet get=new HttpGet(ACCESS_TOKEN_URL);
        JsonParser jsonparer = new JsonParser();
        String result=null;
        try {
            HttpResponse res=client.execute(get);
            String responseContent=null;
            HttpEntity entity=res.getEntity();
            responseContent= EntityUtils.toString(entity,"UTF-8");
            JsonObject json=jsonparer.parse(responseContent).getAsJsonObject();
            System.out.println("access_token:"+json);
            if(res.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                if(json.get("errcode")!=null){
                }else {
                    result=json.get("access_token").getAsString();
                }
            }
        } catch (IOException e) {
            System.out.print(e);
            e.printStackTrace();
        }
        finally {
            {
                /* client.getConnectionManager().shutdown();*/
                Date dt = new Date();
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt);
                String sql="update accesstoken set accessToken='"+result+"', time='"+time+"' where id=1";
                /*xqService.executeSql(sql);*/
                return result;
            }
        }
    }

    /**
     * 辅导员提交宿舍变动提醒
     *
     * sendTemplateMessage
     * @param
     * @throws IOException
     */
    public  boolean sendCheckMessage(String first,String key1,String key2,String key3,String remark,String getUser){
        boolean flag=false;
        String token=getToken();

        String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        WxTemplate temp=new WxTemplate();
        temp.setTouser("o7_PD0-2lXlzjVczkaaCOdE6OSBM");//测试用——lzy
       // temp.setTouser(getUser);
        temp.setTemplate_id(check_template_id);//公司
        temp.setUrl(htmUrl);
        temp.setTopcolor("#FF1217");


        List<HttpRequestUtil.TemplateData> paras=new ArrayList<HttpRequestUtil.TemplateData>();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String nowtime = df.format(new Date());
        paras.add(new HttpRequestUtil.TemplateData("first",first,"#FF3333"));//流程名字
        paras.add(new HttpRequestUtil.TemplateData("keyword1",key1,"#0044BB"));//申请人
        paras.add(new HttpRequestUtil.TemplateData("keyword2",key2,"#0044BB"));//时间
        paras.add(new HttpRequestUtil.TemplateData("keyword3",key3,"#0044BB"));//摘要
        paras.add(new HttpRequestUtil.TemplateData("remark",remark,"#AAAAAA"));

        temp.setData(paras);
        System.out.print(temp.toJSON());
        net.sf.json.JSONObject jsonObject= CommUtil.httpRequest(url,"POST",temp.toJSON());
        if(jsonObject!=null){
            int errorCode=jsonObject.getInt("errcode");
            String errorMessage=jsonObject.getString("errmsg");
            if(errorCode==0){
                flag=true;
            }else {
                System.out.print("模板消息发送失败："+errorCode+","+errorMessage);
                flag=false;
            }
        }
        return flag;
    }


    public String getOpenid(String code) throws DocumentException, JSONException {
        String url = OPENID_BY_CODE_URL + code;
        HttpClient client=new DefaultHttpClient();
        HttpGet get=new HttpGet(url);
        JsonParser jsonparer = new JsonParser();
        String result=null;
        try {
            HttpResponse res=client.execute(get);
            String responseContent=null;
            HttpEntity entity=res.getEntity();
            responseContent= EntityUtils.toString(entity,"UTF-8");
            JsonObject json=jsonparer.parse(responseContent).getAsJsonObject();
            if(res.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                if(json.get("errcode")!=null){
                }else {
                    result=json.get("openid").getAsString();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取jsapi_ticket
     * @return
     */
    public String getJsapiTicket(String token) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
        String params = "access_token=" + token + "&type=jsapi";
        String result = HttpRequestUtils.httpGet(requestUrl + params);
        String jsapi_ticket = JSONObject.parseObject(result).getString("ticket");
        return jsapi_ticket;

    }

    /**
     * 获取图片
     * @param accessToken
     * @param mediaId
     * @return
     */
    public  InputStream getInputStream(String accessToken, String mediaId) {
        InputStream is = null;
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                + accessToken + "&media_id=" + mediaId;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            // 获取文件转化为byte流
            is = http.getInputStream();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;

    }

    /**
     *
     * 获取下载图片信息（jpg）
     *
     * @param mediaId
     *
     *            文件的id
     *
     * @throws Exception
     */

    public  void saveImageToDisk(String accessToken, String mediaId, String picName, String picPath)
            throws Exception {
        InputStream inputStream = getInputStream(accessToken, mediaId);
        byte[] data = new byte[10240];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(picPath+picName+".jpg");
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) throws Exception {
        String accessToken = "17_Gp8oMWgqQ3B5C_YbNhuydMeQbSb_XqgBhcFJMlFB916Wf2JJ6CzlqFe2c6YwIwMpfp7umn88AInx8PRVT-y3yqgwF-9q3yiUNWymzGQ361BBqWJpMmH1bDHgrmyhg1U6f88xz66aSg0mPZ2sYVEjAHAGDM";
        String mediaId = "7N960DZS1uxpYba71qK94vYu5f60WvawyimS9iQIEACveJl6ifbqixKYfcmcdCyu";
        String picName = "";
        /*  saveImageToDisk(accessToken, mediaId, "dd","d:/");*/
    }
}
